# -*- coding: utf-8 -*-
# coding=utf-8
'''
Created on 2014-3-20

@author: SimonFu
'''


import Image
import os
import os.path
import sys

import DBCenter

size_array = [25,52,72,203,350,800,1200]

def Execute():
    root_path = os.path.join(os.getcwd(), 'Style')
    filenames = os.listdir(root_path)
    
    for name in filenames:
        style_id = name
        style_dir = os.path.join(root_path, style_id)
        
        
        #创建图片尺寸目录
        for size in size_array:
#             print style_dir, str(size)
            style_size_path = os.path.join(style_dir, str(size))
            if not os.path.exists(style_size_path):
                os.makedirs(style_size_path)
        
        #得到所有原图
        original_image_file_array = []
        style_filenames = os.listdir(style_dir)     
        for style_name in style_filenames: 
            if(os.path.isfile(os.path.join(style_dir, style_name))):
                original_style_en = {}
                original_style_en['file_name'] = style_name
                original_style_en['file_path'] = os.path.join(style_dir, style_name)
                original_image_file_array.append(original_style_en)
        
        #压缩所有原图
        sort = 1
        for style_file_en in original_image_file_array:
            for size in size_array:
                # 如有老的同名文件，先删除
#                 print style_dir, size, style_file_en.get('file_name')
                size_image_file_path = os.path.join(style_dir, str(size), style_file_en.get('file_name'))
                if(os.path.exists(size_image_file_path)):
                    os.remove(size_image_file_path)
                # 创建图片
                img = Image.open(style_file_en.get('file_path'), 'r')
                img.resize((size,size)).save(size_image_file_path, 'JPEG') 

            # 将图片数据关系写入数据库
            image_file = style_file_en.get('file_name')
            update_flag = False
            if(sort == 1):
                update_flag = True
            else:
                update_flag = False
                
            StyleImageDBOperation(style_id, image_file, sort, update_flag)
            sort = sort + 1
            
            #原图太大，删掉
            os.remove(style_file_en.get('file_path'))
            
    
# 将图片数据写入数据库
def StyleImageDBOperation(style_id, image_file, sort, update_flag):
    # 向数据库insert或update该条图片记录
    
    exist_sql = '''
        SELECT COUNT(1) AS `count`
        FROM `style_image` 
        WHERE `style_id` = '%s' 
            AND `image_src` = '%s'
    ''' % (style_id, image_file)
    count = DBCenter.rc_db.get(exist_sql).get('count');
    
    # 1. style_image
    if count == 0:
        # 插入style_image表
        insert_styleImage_sql = '''
            INSERT INTO `RosefinchEC`.`style_image`
                        (`style_id`,
                         `image_src`,
                         `sort`,
                         `description`,
                         `status`,
                         `create_user`,
                         `create_date`)
            VALUES ('%s',
                    '%s',
                    %s,
                    '',
                    1,
                    'ProductImageCompress',
                    NOW());
        ''' %(style_id, image_file, sort)
        DBCenter.rc_db.execute(insert_styleImage_sql)
    else:
        # update
        pass
    
    # 2. style
    # 更新style表的image字段
    if(update_flag == True):
        update_style_sql = '''
            UPDATE `style`
            SET `image` = '%s'
            WHERE `style_id` = '%s'
        ''' % (image_file, style_id)
        DBCenter.rc_db.execute(update_style_sql)
            
    # 3. item
    # 更新item表的image字段
    if(update_flag == True):
        update_item_sql = '''
            UPDATE `item`
            SET `image` = '%s'
            WHERE `style_id` = '%s'
        ''' % (image_file, style_id)
        DBCenter.rc_db.execute(update_item_sql)
        print update_item_sql
    
Execute()    


